package com.springboot.rigger.common.config;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

public class FilesUtils {

        /**
         * 获取指定目录下面的文件和文件夹
         */
        public static List<File> getAllFiles(String path, FileFilter fileFilter) {
            List<File> allFiles = new ArrayList<File>();
            File file = new File(path);
            if (file.exists()) {
                List<File> fileList = new ArrayList<File>();
                fileList.add(file);
                while (fileList.size() > 0) {
                    allFiles.addAll(fileList);
                    fileList = getNextLevelFiles(fileList, fileFilter);
                }
            }
            return allFiles;
        }

        private static List<File> getNextLevelFiles(List<File> fileList, FileFilter fileFilter) {
            List<File> nextLevelFiles = new ArrayList<File>();
            for (File file : fileList) {
                if (file.isDirectory()) {
                    File[] childs = listFiles(file, fileFilter);
                    if (childs != null) {
                        for (File child : childs) {
                            nextLevelFiles.add(child);
                        }
                    }
                }
            }
            return nextLevelFiles;
        }

        private static File[] listFiles(File file, FileFilter fileFilter) {
            return fileFilter == null ? file.listFiles() : file.listFiles(fileFilter);
        }
    }
